// 用于检测内容、图片是否违规
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const TcbRouter = require('tcb-router')

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({ event })

  app.router('content', async (ctx) => {
    try {
      const result = await cloud.openapi.security.msgSecCheck({
        content: event.content
      })
      if (result.errCode == 0) {
        ctx.body = {
          code: 200,
          errCode: 0,
          msg: result.errMsg
        }
      } else {
        ctx.body = {
          code: 500,
          errCode: result.errCode,
          msg: result.errMsg
        }
      }
    } catch(err) {
      // console.log('err::', err)
      if (err.errCode.toString() === '87014') {
        ctx.body = { code: 500, msg: '内容含有违法违规内容', data: err }
      }
      ctx.body = { code: 502, msg: '调用msgSecCheck接口异常', data: err }
    }
  })

  app.router('img', async (ctx) => {
    try {
      const result = await cloud.openapi.security.imgSecCheck({
        media: {
          contentType: 'image/png',
          value: Buffer.from(event.img)
        }
      })
      if (result && result.errCode.toString() === '87014') {
        ctx.body = { code: 500, msg: '内容含有违法违规内容', data: result }
      } else {
        ctx.body = { code: 200, msg: '内容ok', data: result }
      }
    } catch (err) {
      // 错误处理
      if (err.errCode.toString() === '87014') {
        ctx.body = { code: 500, msg: '内容含有违法违规内容', data: err }
      }
      ctx.body = { code: 502, msg: '调用imgSecCheck接口异常', data: err }
    }
  })


  return app.serve()
}